# -*- coding: utf-8 -*-
from common.email_helper import email_send_with_appendix_list
from common.logger_helper import g_wlogger
from common.pandas_helper import PandasHelper

__author__ = 'sunnychou'
__date__ = '2019/9/10 14:48'

'''
预计付款计划表统计   --- 业务层
'''
import re
from k3_data_report.business.cgyjfk_db import Cgyjfk
from common.utils import format_float, create_uuid

def convert_str_float(snumber):
    try:
        return float("%.2f" % float(snumber))
    except Exception as e:
        return 0

def cgyjfk_gys_process(month):
    '''
     "款到发货" 或者 "款到订货":    ---》  从采购订单获取 价税合计字段
                    "月结" 或者 "月结30天/货到票到30天付款":       ---》  从采购发票获取 价税合计 字段
                    "货到付款": 3   ---  从外购入库获取    ----》 从外购入库 获取 含税金额 字段
    :param month:
    :return:
    '''
    try:
        from k3_data_report.business.cgtj_db import Cgtj
        check_sql = "select distinct tjmonth from k3yjfkjh where tjmonth='%s'" % month
        check_dic = Cgtj.check_cf(check_sql)
        if len(check_dic) > 0:    #有数据，不需要插入
            g_wlogger.winfo(f"cgyjfk_gys_process already existed with month:{month}.")
            return

        #1. 获取采购订单基本信息
        gys_db_rec_dict = Cgyjfk.get_gys_list(month)

        #2. 类型为款到发货，从采购订单获取
        gys_kdfh_rec_dict = Cgyjfk.get_cgyjfk_with_kdfh_list(month)

        #3. 类型为月结（采购发票）
        gys_yuejie_rec_dict = Cgyjfk.get_cgyjfk_with_yuejie_list(month)

        #4. 类型为 外购入库（货到付款）
        gys_waigou_rec_dict = Cgyjfk.get_cgyjfk_with_waigou_list(month)
        hanshui_uprice = 0
        hanshui_jine = 0
        df_data_list_rmb = []
        df_data_list_usd = []
        for gys_db_key  in gys_db_rec_dict.keys():
            (jiesuan_type , bibie, caigou_date,caigou_code,brand,wuliao_name, number,shui_rate) = gys_db_rec_dict[gys_db_key]
            gys_name = gys_db_key.split("#")[0]
            cp_xinhao = gys_db_key.split("#")[1]
            if re.search(r"月结",jiesuan_type) != None:   #从采购发票获取
                yuejie_rec = gys_yuejie_rec_dict.get(gys_db_key, 0)
                (hanshui_uprice, hanshui_jine) =  yuejie_rec if yuejie_rec != 0 else (0, 0)
            elif re.search(r"货到",jiesuan_type) != None:
                wgrk_rec = gys_waigou_rec_dict.get(gys_db_key, 0)
                (hanshui_uprice, hanshui_jine) = wgrk_rec if wgrk_rec != 0 else (0, 0)
            else:            #款到,现金         #从采购订单获取 价税合计字段
                kdfh_rec = gys_kdfh_rec_dict.get(gys_db_key, 0)
                (hanshui_uprice, hanshui_jine) = kdfh_rec if kdfh_rec != 0 else (0, 0)
            if hanshui_uprice == 0:
                continue

            id = create_uuid()
            tjmonth = month
            number = int(float(number))
            hanshui_uprice = convert_str_float(hanshui_uprice)
            hanshui_jine = convert_str_float(hanshui_jine)
            value_tuple = (id, tjmonth, bibie, caigou_date, gys_name, caigou_code, brand, wuliao_name, cp_xinhao,
                           number, shui_rate, hanshui_uprice, hanshui_jine)
            Cgyjfk.insert_cgyjfk(value_tuple)
        g_wlogger.winfo(f"cgyjfk_gys_process store success with：{month}")
        return True
    except Exception as e:
        g_wlogger.werror(f"cgyjfk_gys_process has error:{e}  with:{month}")
        return False

def create_df_cgyjfkrmb(month=None):
        '''
         "款到发货" 或者 "款到订货":    ---》  从采购订单获取 价税合计字段
                        "月结" 或者 "月结30天/货到票到30天付款":       ---》  从采购发票获取 价税合计 字段
                        "货到付款": 3   ---  从外购入库获取    ----》 从外购入库 获取 含税金额 字段
        :param month:
        :return:
        '''
        # 1. 获取采购订单基本信息
        gys_db_rec_dict = Cgyjfk.get_gys_list(month)

        # 2. 类型为款到发货，从采购订单获取
        gys_kdfh_rec_dict = Cgyjfk.get_cgyjfk_with_kdfh_list(month)

        # 3. 类型为月结（采购发票）
        gys_yuejie_rec_dict = Cgyjfk.get_cgyjfk_with_yuejie_list(month)

        # 4. 类型为 外购入库（货到付款）
        gys_waigou_rec_dict = Cgyjfk.get_cgyjfk_with_waigou_list(month)
        hanshui_uprice = 0
        hanshui_jine = 0
        df_data_list_rmb = []
        df_data_list_usd = []
        for gys_db_key in gys_db_rec_dict.keys():
            (jiesuan_type, bibie, caigou_date, caigou_code, brand, wuliao_name, number, shui_rate) = gys_db_rec_dict[
                gys_db_key]
            gys_name = gys_db_key.split("#")[0]
            cp_xinhao = gys_db_key.split("#")[1]
            if re.search(r"月结", jiesuan_type) != None:  # 从采购发票获取
                yuejie_rec = gys_yuejie_rec_dict.get(gys_db_key, 0)
                (hanshui_uprice, hanshui_jine) = yuejie_rec if yuejie_rec != 0 else (0, 0)
            elif re.search(r"货到", jiesuan_type) != None:
                wgrk_rec = gys_waigou_rec_dict.get(gys_db_key, 0)
                (hanshui_uprice, hanshui_jine) = wgrk_rec if wgrk_rec != 0 else (0, 0)
            else:  # 款到,现金         #从采购订单获取 价税合计字段
                kdfh_rec = gys_kdfh_rec_dict.get(gys_db_key, 0)
                (hanshui_uprice, hanshui_jine) = kdfh_rec if kdfh_rec != 0 else (0, 0)
            if hanshui_uprice == 0:
                continue

            id = create_uuid()
            tjmonth = month
            number = int(float(number))
            hanshui_uprice = convert_str_float(hanshui_uprice)
            hanshui_jine = convert_str_float(hanshui_jine)
            value_tuple = (id, tjmonth, bibie, caigou_date, gys_name, caigou_code, brand, wuliao_name, cp_xinhao,
                           number, shui_rate, hanshui_uprice, hanshui_jine)
            email_tuple = (
            caigou_date, gys_name, caigou_code, brand, wuliao_name, cp_xinhao, number, shui_rate, bibie, hanshui_uprice,
            hanshui_jine)
            if bibie == "人民币":
                df_data_list_rmb.append(email_tuple)
        columns = ["采购日期", "供应商", "单据编号", "品牌", "物料名", "规格型号", "数量", "税率", "币别", "含税单价", "价税合计"]
        k3cgyjfk_df_rmb = PandasHelper.create_dataframe(data=df_data_list_rmb, columns=columns)
        return k3cgyjfk_df_rmb


def create_df_cgyjfkusd(month=None):
    '''
     "款到发货" 或者 "款到订货":    ---》  从采购订单获取 价税合计字段
                    "月结" 或者 "月结30天/货到票到30天付款":       ---》  从采购发票获取 价税合计 字段
                    "货到付款": 3   ---  从外购入库获取    ----》 从外购入库 获取 含税金额 字段
    :param month:
    :return:
    '''
    # 1. 获取采购订单基本信息
    gys_db_rec_dict = Cgyjfk.get_gys_list(month)

    # 2. 类型为款到发货，从采购订单获取
    gys_kdfh_rec_dict = Cgyjfk.get_cgyjfk_with_kdfh_list(month)

    # 3. 类型为月结（采购发票）
    gys_yuejie_rec_dict = Cgyjfk.get_cgyjfk_with_yuejie_list(month)

    # 4. 类型为 外购入库（货到付款）
    gys_waigou_rec_dict = Cgyjfk.get_cgyjfk_with_waigou_list(month)
    hanshui_uprice = 0
    hanshui_jine = 0
    df_data_list_rmb = []
    df_data_list_usd = []
    for gys_db_key in gys_db_rec_dict.keys():
        (jiesuan_type, bibie, caigou_date, caigou_code, brand, wuliao_name, number, shui_rate) = gys_db_rec_dict[
            gys_db_key]
        gys_name = gys_db_key.split("#")[0]
        cp_xinhao = gys_db_key.split("#")[1]
        if re.search(r"月结", jiesuan_type) != None:  # 从采购发票获取
            yuejie_rec = gys_yuejie_rec_dict.get(gys_db_key, 0)
            (hanshui_uprice, hanshui_jine) = yuejie_rec if yuejie_rec != 0 else (0, 0)
        elif re.search(r"货到", jiesuan_type) != None:
            wgrk_rec = gys_waigou_rec_dict.get(gys_db_key, 0)
            (hanshui_uprice, hanshui_jine) = wgrk_rec if wgrk_rec != 0 else (0, 0)
        else:  # 款到,现金         #从采购订单获取 价税合计字段
            kdfh_rec = gys_kdfh_rec_dict.get(gys_db_key, 0)
            (hanshui_uprice, hanshui_jine) = kdfh_rec if kdfh_rec != 0 else (0, 0)
        if hanshui_uprice == 0:
            continue

        id = create_uuid()
        tjmonth = month
        number = int(float(number))
        hanshui_uprice = convert_str_float(hanshui_uprice)
        hanshui_jine = convert_str_float(hanshui_jine)
        value_tuple = (id, tjmonth, bibie, caigou_date, gys_name, caigou_code, brand, wuliao_name, cp_xinhao,
                       number, shui_rate, hanshui_uprice, hanshui_jine)
        email_tuple = (
            caigou_date, gys_name, caigou_code, brand, wuliao_name, cp_xinhao, number, shui_rate, bibie, hanshui_uprice,
            hanshui_jine)

        if bibie == "美金":
            df_data_list_usd.append(email_tuple)
    columns = ["采购日期", "供应商", "单据编号", "品牌", "物料名", "规格型号", "数量", "税率", "币别", "含税单价", "价税合计"]

    k3cgyjfk_df_usd = PandasHelper.create_dataframe(data=df_data_list_usd, columns=columns)
    return k3cgyjfk_df_usd

def cgyjfk_gys_process_main(month):
    try:
        cgyjfk_gys_process(month)
        return True
    except Exception as e:
        g_wlogger.werror(f"cgyjfk_gys_process_main has error:{e} with:{month}")
        return False

if __name__ == "__main__":
    month = '2019-07'
    cgyjfk_gys_process(month)




